package com.zpy.wallpaperhsb;

import android.Manifest;
import android.app.Activity;
import android.app.WallpaperInfo;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.os.Bundle;
import android.support.v4.math.MathUtils;
import android.util.Log;
import android.widget.TextView;

public class HSBMainActivity extends BaseActivity {
    private final static String TAG = "HSBMainActivity";
    private TextView mInfoTv;
    private TextView mTitleTv;
    private long mLoadLibTime = 0;


    public BroadcastReceiver wallPaperReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "onReceive:" + action);
            if (action.equals(Intent.ACTION_WALLPAPER_CHANGED)) {
                doWallpaperWork();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hsbmain);
        init();
    }

    @Override
    protected void onResume() {
        super.onResume();
        doWallpaperWork();
    }

    private void init() {
        mInfoTv = (TextView) findViewById(R.id.info);
        mTitleTv = (TextView) findViewById(R.id.title);
        mLoadLibTime = System.currentTimeMillis();
        ImageNativeTool.get();
        mLoadLibTime = System.currentTimeMillis() - mLoadLibTime;
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_WALLPAPER_CHANGED);
        registerReceiver(wallPaperReceiver, intentFilter);

    }



    private void doWallpaperWork() {
        checkPermission(new CheckPermListener() {
                            @Override
                            public void superPermission() {
                                new Thread(new Runnable() {
                                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
                                    @Override
                                    public void run() {
                                        Log.d(TAG, "start doWallpaperWork");
                                        Drawable wallpaper = getWallpaper(HSBMainActivity.this);
                                        if (wallpaper != null) {
                                            Bitmap scaleBitmep = scaleMatrix(drawable2bitmap(wallpaper), 0.05f, 0.05f);
                                            long timeJava = System.currentTimeMillis();
                                            final int brightJava = getBright(scaleBitmep); //亮度
                                            final float hueJava = getHue(scaleBitmep); //色相
                                            final float saturationJava = getSaturation(scaleBitmep);//饱和度
                                            timeJava = System.currentTimeMillis() - timeJava;



                                            long timeJni = System.currentTimeMillis();
                                            final int brightJni = ImageNativeTool.get().getBitmapBright(scaleBitmep);
                                            final float hueJni = ImageNativeTool.get().getBitmapHue(scaleBitmep);
                                            final float saturationJni = ImageNativeTool.get().getBitmapSaturation(scaleBitmep);
                                            timeJni = System.currentTimeMillis() - timeJni;

                                            final long finalTimeJava = timeJava;
                                            final long finalTimeJni = timeJni;
                                            Log.d(TAG, "brightJava:" + brightJava + ",brightJni:" + brightJni);
                                            mInfoTv.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    String info = "Bright(java):" + brightJava
                                                            + "\nhueJava:" + hueJava
                                                            + "\nsaturationJava:" + saturationJava
                                                            + "\n,time:" + finalTimeJava + "ms"
                                                            + "\n" + "Bright(jni):" + brightJni
                                                            + "\nhueJni:" + hueJni
                                                            + "\nsaturationJni:" + saturationJni
                                                            + "\n,time:" + finalTimeJni  + "ms-loadlibTime:" + mLoadLibTime + "ms";
                                                    mInfoTv.setText(info);
                                                    Log.d(TAG, "info:" + info);
                                                }
                                            });
                                        }
                                        Log.d(TAG, "doWallpaperWork end");
                                    }
                                }).start();

                            }
                        }, R.string.ask_again,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

    }



    public static Bitmap scaleMatrix(Bitmap bitmap, float scaleX, float scaleY){
        Log.d(TAG, "scaleMatrix start");
        try {
            int w = bitmap.getWidth();
            int h = bitmap.getHeight();
            float scaleW = scaleX;
            float scaleH = scaleY;
            Matrix matrix = new Matrix();
            matrix.postScale(scaleW, scaleH); // 长和宽放大缩小的比例
            Bitmap scaleBitmap =  Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, false);
            Log.d(TAG, "scaleMatrix normal end");
            return scaleBitmap;

        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(TAG, "scaleMatrix error end");
        return bitmap;

    }

    private Bitmap drawable2bitmap(Drawable drawable) {
        BitmapDrawable bd = (BitmapDrawable) drawable;
        return bd.getBitmap();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private Drawable getWallpaper(Context context) {
        WallpaperManager wm = WallpaperManager.getInstance(context);
        final WallpaperInfo wallpaperInfo = wm.getWallpaperInfo();
        if (wallpaperInfo != null) {
            final Drawable drawable = wallpaperInfo.loadThumbnail(getPackageManager());
            mTitleTv.post(new Runnable() {
                @Override
                public void run() {
                    mTitleTv.setText(R.string.livewallpaper);
                }
            });
            return drawable;
        }
        mTitleTv.post(new Runnable() {
            @Override
            public void run() {
                mTitleTv.setText(R.string.norwallpaper);
            }
        });
        Log.d(TAG, "WallpaperInfo:" + wallpaperInfo);
        return wm.getDrawable();
    }


    //获取图片亮度 范围（0～255）
    private int getBright(Bitmap bm) {
        Log.d(TAG, "getBright start");
        if(bm == null) return -1;
        int width = bm.getWidth();
        int height = bm.getHeight();
        int r, g, b;
        int count = 0;
        int bright = 0;
        count = width * height;
        int[] buffer = new int[width * height];

        bm.getPixels(buffer, 0, width, 0, 0, width , height);
        Log.d(TAG, "width:" + width + ",height:" + height);
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                int localTemp = buffer[j * width + i];//bm.getPixel(i, j);
                r = (localTemp >> 16) & 0xff;
                g = (localTemp >> 8) & 0xff;
                b = localTemp & 0xff;
                bright = (int) (bright + 0.299 * r + 0.587 * g + 0.114 * b);
            }
        }
        Log.d(TAG, "getBright end");
        return bright / count;
    }

    //获取图片色相Hue 范围（0～1）
    private float getHue(Bitmap bm) {
        Log.d(TAG, "getHue start");
        if(bm == null) return -1;
        int width = bm.getWidth();
        int height = bm.getHeight();
        int r, g, b;
        int count = 0;
        float hue = 0;
        float hueSum = 0;
        count = width * height;
        int[] buffer = new int[width * height];

        bm.getPixels(buffer, 0, width, 0, 0, width , height);
        Log.d(TAG, "width:" + width + ",height:" + height);
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                int localTemp = buffer[j * width + i];//bm.getPixel(i, j);
                r = (localTemp >> 16) & 0xff;
                g = (localTemp >> 8) & 0xff;
                b = localTemp & 0xff;

                int max = Math.max(Math.max(r,g),b);
                int min = Math.min(Math.min(r,g),b);


                if (r == max) {
                    hue = (max - min) == 0 ? 0 : ((g - b) / (float) (max - min));
                }
                if (g == max) {
                    hue = 2 + ((max - min) == 0 ? 0 : ((b - r) / (float) (max - min)));

                }
                if (b == max) {
                    hue = 4 + ((max - min) == 0 ? 0 : ((r - g) / (float) (max - min)));

                }
                hue = (hue / 6f);

                if (hue < 0) {
                    hue = (hue / 360f + 1);
                }

                hueSum += hue;


            }
        }
        Log.d(TAG, "getHue end");
        return hueSum / (float) count;
    }

    //获取图片饱和度Saturation 范围（0～1）
    private float getSaturation(Bitmap bm) {
        Log.d(TAG, "getSaturation start");
        if(bm == null) return -1;
        int width = bm.getWidth();
        int height = bm.getHeight();
        int r, g, b;
        int count = 0;
        float saturation = 0;
        count = width * height;
        int[] buffer = new int[width * height];

        bm.getPixels(buffer, 0, width, 0, 0, width , height);
        Log.d(TAG, "width:" + width + ",height:" + height);
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                int localTemp = buffer[j * width + i];//bm.getPixel(i, j);
                r = (localTemp >> 16) & 0xff;
                g = (localTemp >> 8) & 0xff;
                b = localTemp & 0xff;

                int max = Math.max(Math.max(r,g),b);
                int min = Math.min(Math.min(r,g),b);


                saturation += max == 0? 0 : (max - min) / (float)max;

            }
        }
        Log.d(TAG, "getSaturation end");
        return saturation / (float) count;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(wallPaperReceiver);
    }
}
